package cn.chuanw.wx.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import cn.chuanw.wx.annotation.RequiresPermissionsDesc;
import cn.chuanw.core.util.RandomNumberUtil;
import cn.chuanw.core.util.ResponseUtil;
import cn.chuanw.db.dao.WIncomerentRecordMapper;
import cn.chuanw.db.dao.WTenantInfoMapper;
import cn.chuanw.db.domain.WIncomerentRecord;
import cn.chuanw.db.domain.WTenantInfo;
import cn.chuanw.db.domain.WTenantInfoExample;
import cn.chuanw.db.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin/tenant")
@Validated
public class TenantController {
    private final Log logger = LogFactory.getLog(TenantController.class);

    @Autowired
    private TenantService tenantService;
    @Resource
    private WIncomerentRecordMapper wIncomerentRecordMapper;
    @Resource
    private WTenantInfoMapper wTenantInfoMapper;

    @RequiresPermissions("admin:tenant:list")
    @RequiresPermissionsDesc(menu = {"公寓管理", "租户信息"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(value = "tenantName", required = false) String tenantName,
                       @RequestParam(value = "houseId", required = false) String houseId,
                       @RequestParam(value = "roomId", required = false) String roomId,
                       @RequestParam(value = "tenantStauts", required = false) Integer tenantStauts,
                       @RequestParam(value = "payrentStatus", required = false) Integer payrentStatus,
                       @RequestParam(value = "payDate", required = false) String payDate,
                       @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer limit) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = null;
        if (!StringUtils.isEmpty(payDate)) {
            localDate = LocalDate.parse(payDate, formatter);
        }
        List<WTenantInfo> wTenantInfos = tenantService.querySelective(tenantName,houseId, roomId, tenantStauts, payrentStatus,
                localDate, page, limit);

        return ResponseUtil.okList(wTenantInfos);
    }

    //
    @RequiresPermissions("admaddin:tenant:renovate")
    @RequiresPermissionsDesc(menu = {"公寓管理", "租户信息刷新"}, button = "刷新")
    @GetMapping("/renovate")
    public Object renovate() {
        List<WTenantInfo> wTenantInfos = tenantService.playFlagUpdate();
        return ResponseUtil.okList(wTenantInfos);
    }

    @RequiresPermissions("admaddin:tenant:create")
    @RequiresPermissionsDesc(menu = {"公寓管理", "租户信息"}, button = "新增")
    @PostMapping("/create")
    public Object add(@RequestBody WTenantInfo wTenantInfo) {
        wTenantInfo.setCreateTime(LocalDateTime.now());
        wTenantInfo.setUpdateTime(LocalDateTime.now());
        wTenantInfo.setId(RandomNumberUtil.getStringRandom(12));
        tenantService.addTenantInfo(wTenantInfo);
        return ResponseUtil.ok(wTenantInfo);
    }

    @RequiresPermissions("admaddin:tenant:update")
    @RequiresPermissionsDesc(menu = {"公寓管理", "租户信息"}, button = "修改")
    @PostMapping("/update")
    public Object update(@RequestBody WTenantInfo wTenantInfo) {
        wTenantInfo.setUpdateTime(LocalDateTime.now());
        tenantService.updateById(wTenantInfo);
        return ResponseUtil.ok(wTenantInfo);
    }

    @GetMapping("/options")
    public Object options() {
        List<WTenantInfo> wTenantInfos = tenantService.queryAll();

        List<Map<String, Object>> options = new ArrayList<>(wTenantInfos.size());
        for (WTenantInfo wTenantInfo : wTenantInfos) {
            Map<String, Object> option = new HashMap<>(2);
            option.put("value", wTenantInfo.getId());
            option.put("label", wTenantInfo.getTenantName());
            options.add(option);
        }
        return ResponseUtil.okList(options);
    }

    @RequiresPermissionsDesc(menu = {"公寓管理", "租户信息"}, button = "新增收租记录")
    @PostMapping("/createIncomeRenById")
    public int addIncomeRenById() {
        WTenantInfoExample wTenantInfoExample = new WTenantInfoExample();
        WTenantInfoExample.Criteria criteria = wTenantInfoExample.createCriteria();
        criteria.andDelFlagEqualTo(0);
        // 查询所有租客信息
        List<WTenantInfo> wTenantInfos = wTenantInfoMapper.selectByExample(wTenantInfoExample);
        int number = 0;
        for (WTenantInfo wTenantInfo : wTenantInfos) {
            number++;
            //获取首月时间
            if (wTenantInfo.getFirstRentment() != null) {
                LocalDate localDate = LocalDate.of(wTenantInfo.getFirstRentment().getYear()
                        , wTenantInfo.getFirstRentment().getMonthValue()
                        , wTenantInfo.getFirstRentment().getDayOfMonth());


                WIncomerentRecord wIncomerentRecord = new WIncomerentRecord();
                wIncomerentRecord.setRoomId(wTenantInfo.getRoomId());
                wIncomerentRecord.setHouseId(wTenantInfo.getHouseId());
                wIncomerentRecord.setId(RandomNumberUtil.getStringRandom(12));
                wIncomerentRecord.setTenantId(wTenantInfo.getId());
                //合同开始时间到结束时间allMonth
                int beginAllMonth = wTenantInfo.getBeginDate().getYear() * 12 + wTenantInfo.getBeginDate().getMonthValue();
                int endAllMonth = wTenantInfo.getEndDate().getMonthValue() + wTenantInfo.getEndDate().getYear() * 12;
                int allMonth = endAllMonth - beginAllMonth;

                // 插入首月收租时间  如果一把付清只插入首月支付時間
                wIncomerentRecord.setIncomeTime(localDate);
                wIncomerentRecordMapper.insertSelective(wIncomerentRecord);

                if (wTenantInfo.getRentCycle() == 1) {
                    for (int i = 1; i <= allMonth; i++) {
                        wIncomerentRecord.setId(RandomNumberUtil.getStringRandom(12));
                        wIncomerentRecord.setIncomeTime(localDate.plusMonths(i));
                        wIncomerentRecordMapper.insertSelective(wIncomerentRecord);
                    }
                    //押一付二
                } else if (wTenantInfo.getRentCycle() == 2) {
                    //交租次数,比如12月租期押一付二,初次交租每次递增2个月
                    int paymentName = allMonth / 2;
                    //i是 1-6  2次交租+2，3次交租+4 4次交租+6
                    for (int i = 1; i < paymentName; i++) {
                        wIncomerentRecord.setId(RandomNumberUtil.getStringRandom(12));
                        wIncomerentRecord.setIncomeTime(localDate.plusMonths(i * 2));
                        wIncomerentRecordMapper.insertSelective(wIncomerentRecord);
                    }
                    //押一付三
                } else if (wTenantInfo.getRentCycle() == 3) {
                    //交租次数,比如24月租期押一付三生成8次交租记录,从初次交租每次递增3个月,1,4,7,10,13
                    int paymentName = allMonth / 3;
                    for (int i = 1; i < paymentName; i++) {
                        wIncomerentRecord.setId(RandomNumberUtil.getStringRandom(12));
                        //i是交租次数， 2次+3 3次+6 4次+9 5次+12
                        wIncomerentRecord.setIncomeTime(localDate.plusMonths(i * 3));
                        wIncomerentRecordMapper.insertSelective(wIncomerentRecord);
                    }
                }
                //半年付
                else if (wTenantInfo.getRentCycle() == 6) {
                    //交租次数,比如24月租期押一付三生成8次交租记录,从初次交租每次递增3个月,1,4,7,10,13
                    int paymentName = allMonth / 6;
                    for (int i = 1; i < paymentName; i++) {
                        //i是交租次数， 2次+3 3次+6 4次+9 5次+12
                        wIncomerentRecord.setIncomeTime(localDate.plusMonths(i * 6));
                        wIncomerentRecordMapper.insertSelective(wIncomerentRecord);
                    }
                }
            }
        }
        return number;


    }
}
